package com.epam.client.backingbeans;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

import com.epam.DAO.BillDAO;
import com.epam.DAO.ClientDAO;
import com.epam.DAO.RequestDAO;
import com.epam.entity.Bill;
import com.epam.entity.Client;
import com.epam.entity.Request;
import com.epam.entity.Status;

public class BillsManageBean {

	@EJB
	private BillDAO billDAO;
	@EJB
	private RequestDAO requestDAO;
	@EJB
	private ClientDAO clientDAO;
	@Resource
	UserTransaction ut;
	
	private DataModel<Bill> bills;
	private Bill bill;

	private int firstRow;
	private int totalPages;
	private int currentPage;

	private int rowsPerPage = 5; 
	private int totalRows;
	
	public BillsManageBean() {
		bills = new ListDataModel<Bill>();
	}

	public void pageFirst() {
        page(0);
    }

    public void pageNext() {
        page(firstRow + rowsPerPage);
    }

    public void pagePrevious() {
        page(firstRow - rowsPerPage);
    }

    public void pageLast() {
        page(totalRows - ((totalRows % rowsPerPage != 0) ? totalRows % rowsPerPage : rowsPerPage));
    }

    private void page(int firstRow) {
        this.firstRow = firstRow;
    }
	
    public int getTotalRows() {
        return totalRows;
    }

    public int getFirstRow() {
        return firstRow;
    }

    public int getRowsPerPage() {
        return rowsPerPage;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public int getTotalPages() {
        return totalPages;
    }
	
	public DataModel<Bill> getBills() {
		Client client = clientDAO.read();
		bills.setWrappedData(billDAO.getUserBills(client, firstRow, rowsPerPage, Status.NOT_PAYED));
		
		totalRows = billDAO.getUserBillsCount(client, Status.NOT_PAYED);
		// Set currentPage, totalPages and pages.
		currentPage = (totalRows / rowsPerPage) - ((totalRows - firstRow) / rowsPerPage) + 1;
        totalPages = (totalRows / rowsPerPage) + ((totalRows % rowsPerPage != 0) ? 1 : 0);
		
		return bills;
	}

	public void initBill() {
		bill = bills.getRowData();
	}

	public void payBill() throws IllegalStateException, SecurityException, SystemException {
		try {
			ut.begin();

			Request request = bill.getRequest();
			request.setStatus(Status.ACTIVE);
			requestDAO.update(request);

			bill.setStatus(Status.PAYED);
			billDAO.update(bill);

			ut.commit();
		} catch (Exception e) {
			ut.rollback();
		}
	}

}
